$(document).ready(function(){
	$('#originalContentToogle').click(function(){
		var originalContentDiv = $('#originalContentDiv').get(0);
		if(originalContentDiv.isShown) {
			$(originalContentDiv).hide();
			originalContentDiv.isShown = false
		} else {
			$(originalContentDiv).show();
			originalContentDiv.isShown = true
		}
	});
	
	$('#extractButton').click(function(){
		$('#extractResultDiv').get(0).innerHTML = "Extracting ...";
		$.post('regExpExtract.ajax',
			{
				extractorName: $('#extractorName').get(0).value,
				regularExpression: $('#regularExpression').get(0).value,
				trimNewLine: $('#trimNewLine').get(0).checked
			},
			function(data){
				$('#extractResultDiv').get(0).innerHTML = "Extracted Result is: " + data;
			}
		);
		
		refreshExtractorList();
	});
	
	$('#convertSelectionButton').click(function(){
		var selectedText = String(wdxGetSelectionText());
		alert(selectedText);
		
		var regExp = wdxEscapeRegExp(selectedText).replace($('#selectedText').get(0).value, '(.+)');
		$('#regularExpression').get(0).value = regExp;
	});
	
	$('#generateButton').click(function(){
		window.location = 'generator.wdx';
	});
});

function refreshExtractorList() {
	$.getJSON('getContentExtractorList.ajax',
		function(nameList){
			var names = '';
			for(var i=0; i<nameList.length; i++) {
				names += '<li>' + nameList[i] + ' <input type="button" id="remove' + nameList[i] + '" class="removeExtractorButton" value="remove"/></li>';
			}
			$('#extractorListDiv').get(0).innerHTML = '<ul>' + names + '</ul>';
			wdxRefreshRemoveButtonBinding();
		}
	);
}

function wdxRefreshRemoveButtonBinding() {
	$('.removeExtractorButton').unbind('click');
	$('.removeExtractorButton').click(function(){
		$.get('removeContentExtractor.ajax', {extractorName: this.id.substr(6)});

		refreshExtractorList();
	});
}

function wdxEscapeRegExp(patternText) {
	var specialChars = ".|*?+(){}[]^$\\"

	var pattern = "";
	for(var i=0; i<patternText.length; i++) {
		if(specialChars.indexOf(patternText.charAt(i)) >= 0) {
			pattern = pattern + "\\" + patternText.charAt(i);
		} else {
			pattern = pattern + patternText.charAt(i);
		}
	}
	return pattern;
}



// TODO this is duplicated in select.js, merge it sometimes
function wdxGetSelectionText() {
	if (window.getSelection) {
		return window.getSelection();
	}
	else if (document.getSelection) {
		return document.getSelection();
	}
	else if (document.selection) {
		return document.selection.createRange().text;
	}
	else return null;
}